// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import { syncCode } from './syncCode';
import { componentCompile } from './componentCompile';
import { prebuildDownload } from './prebuildDownload';
import { downloadImage } from './downloadImage';
import { deleteImage } from './deleteImage';
import path from 'path';
import fs from 'fs';
import { ReGenerateImagePanel } from './ReGenerateImage/ReGenerateImagePanel';
import { pushFileToDevice } from './pushFileToDevice/pushFileToDevice';
import { HiLogViewProvider } from './HiLog/HiLogViewProvider';
import { HiLogService } from './HiLog/HiLogService';

// 检查文件夹是否包含 bundle.json
async function hasBundleJson(folderPath: string): Promise<boolean> {
	const targetFile = path.join(folderPath, 'bundle.json');
	try {
	  await fs.promises.access(targetFile, fs.constants.F_OK);
	  return true;
	} catch {
	  return false;
	}
}

// 装饰器提供程序
class BundleIndicatorProvider implements vscode.FileDecorationProvider {
	private _onDidChange = new vscode.EventEmitter<vscode.Uri[]>();
	readonly onDidChangeFileDecorations = this._onDidChange.event;
  
	// 当需要更新装饰时调用
	refresh(uris: vscode.Uri[]) {
	  this._onDidChange.fire(uris);
	}
  
	// 核心装饰逻辑
	async provideFileDecoration(uri: vscode.Uri): Promise<vscode.FileDecoration | undefined> {
	  if (uri.scheme !== 'file') {
		return;
	  }

	  const stat = await vscode.workspace.fs.stat(uri);
	  
	  // 为 bundle.json 文件提供装饰
	  if (stat.type === vscode.FileType.File && path.basename(uri.fsPath) === 'bundle.json') {
		return {
		  badge: '📦',
		  tooltip: 'Bundle JSON File',
		  color: new vscode.ThemeColor('charts.orange')
		};
	  }
	  
	  // 为包含 bundle.json 的文件夹提供装饰
	  if (stat.type === vscode.FileType.Directory) {
		const hasBundle = await hasBundleJson(uri.fsPath);
		return hasBundle ? {
		  badge: '📦',
		  tooltip: 'Component Folder with bundle.json',
		  color: new vscode.ThemeColor('charts.blue'),
		  propagate: false
		} : undefined;
	  }
	  
	  return undefined;
	}
  }

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	const provider = new BundleIndicatorProvider();
	const watcher = vscode.workspace.createFileSystemWatcher('**/bundle.json');
  
	// 注册装饰器
	context.subscriptions.push(
	  vscode.window.registerFileDecorationProvider(provider)
	);
  
	// 监听 bundle.json 变化
	const refreshParentFolder = (uri: vscode.Uri) => {
	  const parentUri = vscode.Uri.file(path.dirname(uri.fsPath));
	  provider.refresh([parentUri]);
	};
  
	watcher.onDidCreate(refreshParentFolder);
	watcher.onDidDelete(refreshParentFolder);
	
	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "component-compile" is now active!');

	// Register HiLog view provider
	const hiLogViewProvider = new HiLogViewProvider(context.extensionUri);
	context.subscriptions.push(
		vscode.window.registerWebviewViewProvider(
			HiLogViewProvider.viewType,
			hiLogViewProvider
		)
	);

	const hiLogService = HiLogService.getInstance();
	context.subscriptions.push({
		dispose: () => {
			hiLogService.stopDeviceMonitoring();
		}
	});

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	context.subscriptions.push(vscode.commands.registerCommand('component-compile.syncCode', (...args: any[]) => {
		syncCode(args);
	}));
	
	context.subscriptions.push(vscode.commands.registerCommand('component-compile.componentCompile', (...args: any[]) => {
		componentCompile(context, args);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.prebuild-download-option1', (...args: any[]) => {
		prebuildDownload(args, true);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.prebuild-download-option2', (...args: any[]) => {
		prebuildDownload(args, false);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.download-image', (...args: any[]) => {
		downloadImage('https://cidownload.openharmony.cn/version/Master_Version/OpenHarmony_5.1.0.63/20250509_020348/version-Master_Version-OpenHarmony_5.1.0.63-20250509_020348-ohos-sdk-full.tar.gz');
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.delete-image', (...args: any[]) => {
		deleteImage();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.regenerateImage', (...args: any[]) => {
		ReGenerateImagePanel.createOrShow(context.extensionUri);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.pushFileToDevice', (...args: any[]) => {
		pushFileToDevice(args, context);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.showHiLog', (...args: any[]) => {
		// Focus the HiLogViewProvider view
		vscode.commands.executeCommand('hiLogView.focus');
	}));
}

// This method is called when your extension is deactivated
export function deactivate() {}
